// pages/handover/index.ts
import request from '../../utils/request'
import drawQrcode from 'weapp-qrcode-canvas-2d'
import {base64Encode, base64Decode} from '../../utils/base64'
const app = getApp<IAppOption>()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        globalData: {},

        deviceList: [],// 绑定的设备
        allSelected: false,// 全选
        selectData: [],// 选中的数据
        
        popup: {},// 提示框

        start: "CJKJ-",// 二维码内容开头
        showQr: false,// 设备移交二维码展示框
        qrSrc: '',// 二维码图片地址
        
        qrData: [],// 扫描移交二维码得到的设备号数据
        showQrResult: false,
    },

    /**
     * 全选/取消全选
     * @param e 
     */
    selectAll(e: any) {
        const deviceList = this.data.deviceList;
        const values: any = [];
        if(! this.data.allSelected){  //全选
            deviceList.forEach( obj => {
                obj.checked = true
                values.push(obj.equipmentNo);
            })
        } else {  //取消全选，即全不选
            deviceList.forEach( obj => {
                obj.checked = false
            })
        }
        this.setData({
            allSelected: !this.data.allSelected,
            deviceList: deviceList,
            selectData: values
        })
    },
    /**
     * 选中/取消选中设备
     * @param e 
     */
    checkboxChange(e: any) {
        const values = e.detail.value
        // 判断是否全选
        let flag = false;
        if(values && values.length === this.data.deviceList.length) {
            flag = true;
        }
        this.setData({
            allSelected: flag,
            selectData: values
        })
    },
    // 加载绑定的设备
    getData(option : string){
        let that = this;
        request.get('/applet/bind-info/list?dataType='+app.globalData.dataType).then((res: any) => {
            if(res.data.code === 200) {

                let data = res.data.data;
                let list:any = [];
                if(data && data.length > 0) {
                    data.forEach(val => {
                        list.push({
                            checked: false,
                            equipmentNo: val,
                        });
                    });
                } else {
                    if(option === 'yj') {
                        // 移交过后查询数据
                        // 如果没有设备了，说明是全部移交，此时将医生账号置空
                        app.globalData.doctorAccount = "";
                        wx.setStorageSync('doctorAccount', "");
                    }
                }
                that.setData({
                    deviceList: list
                });
            }
        })
    },

    doSubmit(){
        let data = this.data.selectData
        if(data.length <= 0) {
            this.setData({
                popup: {
                    idx: Math.random(),
                    show: true,
                    title: '提 示',
                    msg: '请先选择设备再移交！',
                    icon: '../../static/img/no_happy.png'
                },
            })
            return ;
        }
        this.createCode(this.data.start + base64Encode(data.join(",")));
    },
    /**
     * 创建二维码
     */
    createCode(content: string) {

        if(!content) {
            wx.showToast({
                title: '二维码内容为空',
                icon: 'error',
                duration: 2000
            })
            return 
        }

        var that = this;
        wx.createSelectorQuery()
        .select('#myQrcode')
        .fields({
            node: true,
            size: true
        })
        .exec((res) => {
            var canvas = res[0].node;
            var img = canvas.createImage();
            img.src = "../../static/img/wx_logo.png";
            img.onload = function () {
                // img.onload完成后才能调用 drawQrcode方法
                var options = {
                    canvas: canvas,
                    canvasId: 'myQrcode',
                    width: 200,
                    padding: 0,
                    paddingColor: '#fff',
                    background: '#fff',
                    foreground: '#000000',
                    text: content,
                    image: {
                        imageResource: img,
                        width: 40, // 建议不要设置过大，以免影响扫码
                        height: 40, // 建议不要设置过大，以免影响扫码
                        round: true // Logo图片是否为圆形
                    }
                }
                drawQrcode(options)
                // 获取临时路径（得到之后，想干嘛就干嘛了）
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 200,
                    height: 200,
                    destWidth: 200,
                    destHeight: 200,
                    canvasId: 'myQrcode',
                    canvas: canvas,
                    success(res) {
                        that.setData({
                            qrSrc: res.tempFilePath,
                            showQr: true,
                        })
                    },
                    fail(res) {
                        console.error(res)
                    }
                })
            };
        })
    },
    // 关闭二维码
    onQrClose(){
        this.setData({
            selectData: [],
            allSelected: false,
            showQr: false,
        });
        this.getData('yj');
    },

    // 扫描移交二维码
    handleScan() {
        wx.scanCode({
            success: (res) => {
                let content = res.result;
                if(! content.startsWith(this.data.start)) {
                    this.setData({
                        popup: {
                            idx: Math.random(),
                            show: true,
                            title: '提 示',
                            msg: '无法识别该二维码！',
                            icon: '../../static/img/no_happy.png'
                        },
                    })
                } else {
                    content = content.replace(this.data.start, "");
                    let dataStr = base64Decode(content);
                    let datas = dataStr.split(",");

                    let arr: any = [];
                    datas.forEach(v => {
                        arr.push(v.replace(/[^\w\s]/gi, ''));
                    });
                    this.setData({
                        showQrResult: true,
                        qrData: arr
                    });
                }
            }
        })
    },

    closeQrResult(){
        this.setData({
            showQrResult: false,
        })
    },

    receive(){
        let that = this;
        wx.showLoading({
            title: '请求中...',
        });
        request.post('/applet/bind-info/receive',  this.data.qrData).then((res: any) => {
            wx.hideLoading();
            
            // 保存医生账号信息
            app.globalData.doctorAccount = res.data.data
            wx.setStorageSync('doctorAccount', app.globalData.doctorAccount);

            that.setData({
                popup: {
                    idx: Math.random(),
                    show: true,
                    title: '提 示',
                    msg: '设备接收成功！',
                    icon: '../../static/img/smile.png'
                },
                showQrResult: false,
            });
            that.getData('');
            
        })
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            globalData: app.globalData
        });

        this.getData('');
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})